//
//  YDBuyStrategyTableHeaderView.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2017/11/15.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDBuyStrategyTableHeaderView.h"
#import "YDAccountMonyModel.h"



@interface YDBuyStrategyTableHeaderView()
//申请资金
@property (nonatomic , weak) UILabel *fundLabel;
//按钮框
@property (nonatomic , weak) UIView *fundButtonsView;

//计算的股数和资金利用率
@property (nonatomic , weak) UILabel *stockRate;

//分割线
@property (nonatomic , weak) UIView *lineV1;

//履约保证金
@property (nonatomic , weak) UILabel *bondLabel;

@property (nonatomic , weak) UIView *bondButtonsView;

//分割线
@property (nonatomic , weak) UIView *lineV2;

//存放申请资金btn的数组
@property (nonatomic, strong)NSMutableArray *fundBtnArr;

//存放履约金btn数组
@property (nonatomic, strong)NSMutableArray *bondBtnArr;

@end

@implementation YDBuyStrategyTableHeaderView

-(void)setStockMarket:(NSDictionary *)stockMarket
{
    _stockMarket = stockMarket;
}
-(void)setFundsArray:(NSArray *)fundsArray
{
    _fundsArray = fundsArray;
    
    
    //整个按钮区域的宽度
    CGFloat buttonsViewW = rate375(284);
    //按钮间的横向间距
    CGFloat marginH = rate375(14);
    //按钮间的竖向间距
    CGFloat marginV = isPhoneX ? rateX812(13) : rate750(13);
    //按钮的高度
    CGFloat buttonH = isPhoneX ? rateX812(24) : rate750(24);
    
    [self.fundBtnArr removeAllObjects];
    
    if (self.fundButtonsView) {
        for (UIView *view in self.fundButtonsView.subviews) {
            [view removeFromSuperview];
        }
    }
    //只有一个申请资金
//    if (fundsArray.count == 1) {
//
//         PZNoHeightedButton *button = [self createBtnWithFundModel:fundsArray.firstObject];
//        button.frame = CGRectMake(0, 0, rate375(60), buttonH);
//
//        [self.fundButtonsView addSubview:button];
//
//        [self.fundBtnArr addObject:button];
//
//        //[self.fundButtonsView layoutIfNeeded];
//        [self.fundButtonsView mas_updateConstraints:^(MASConstraintMaker *make) {
//            make.height.equalTo(@(buttonH));
//        }];
//
//        return;
//    }
    
    NSInteger lastLie = 0;
    for (int i = 0; i < fundsArray.count; i ++) {
        
        //每行显示的个数
        NSInteger cows = 4;
        //按钮的宽度
        CGFloat buttonW = (buttonsViewW - (cows - 1)*marginH) / cows;
        
        
        
        //确定第几列第几行
        NSInteger whichCow = i / cows;
        NSInteger whichCol = i % cows;
        
        if (i == fundsArray.count - 1) {
            //最后一个button在那一列
            lastLie = whichCow + 1;
        }
        
        
        //确定按钮的x  y
        
        CGFloat buttonX = whichCol * (marginH + buttonW );
        CGFloat buttonY = whichCow * (marginV + buttonH );
        
        YDAccountMonyModel *model  = fundsArray[i];
        SYNoHeightedButton *button = [self createBtnWithFundModel:model];
        
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
       
        [self.fundButtonsView addSubview:button];
        
        button.tag = i;
        [self.fundBtnArr addObject:button];
        
    }
    //更新高度
    [self.fundButtonsView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(buttonH * lastLie + marginV *(lastLie -1)));
    }];
    
    
}


/**
 动态返回headview的高度
 */
+(CGFloat )headviewHeightWithData:(NSArray *)fundArr
{
    //按钮的高度
    CGFloat buttonH = isPhoneX ? rateX812(24) : rate750(24);
    //按钮间的竖向间距
    CGFloat marginV = isPhoneX ? rateX812(13) : rate750(13);
    
    //计算总共多少列
     NSInteger lastCow = (fundArr.count- 1) / 4 + 1;
    
    CGFloat funViewHeight = buttonH * lastCow + marginV *(lastCow - 1);
    
    
    //头视图总高度 fundviewH + 可选多少股viewH + 间隙 后两者是死的
    return funViewHeight + (isPhoneX ? rateX812(57) : rate750(57));
    
    
}


/**
 返回对应model的申请资金按钮
 */
- (SYNoHeightedButton *)createBtnWithFundModel:(YDAccountMonyModel *)model
{
    SYNoHeightedButton *button =  [SYNoHeightedButton buttonWithType:UIButtonTypeCustom];
    button.titleLabel.font = [UIFont systemFontOfSize:font12ScreenWRate * LKScreenW];
    button.titleLabel.adjustsFontSizeToFitWidth = YES;
    button.backgroundColor = [UIColor clearColor];
    // NSString *wan =   [model.value substringWithRange:NSMakeRange(0, model.value.length - 4)];
    [button setTitle:[NSString stringWithFormat:@"%@ 万", model.wanValue] forState:UIControlStateNormal];
    
    //按钮颜色
    [button setTitleColor:[UIColor colorWithHexString:blueyGrey] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    //背景
    [button setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:fadedOrange]] forState:UIControlStateSelected];
    //边框
    button.layer.cornerRadius = 3.0f;
    button.layer.masksToBounds = YES;
    button.layer.borderWidth = 1.0f;
    button.layer.borderColor = [UIColor colorWithHexString:blueyGrey].CGColor;
    [button addTarget:self action:@selector(fundBtnDidSelected:) forControlEvents:UIControlEventTouchUpInside];
    return button;
}
-(void)setCurrentMoney:(NSString *)currentMoney
{
    _currentMoney = currentMoney;
    
    if (currentMoney.length) {
        [self.fundBtnArr enumerateObjectsUsingBlock:^(UIButton*  obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([[NSString stringWithFormat:@"%@ 万",currentMoney] isEqualToString:obj.titleLabel.text ]) {
                obj.selected = YES;
                obj.layer.borderWidth = 1.0f;
                obj.layer.borderColor = [UIColor clearColor].CGColor;
                [self reLoadDetailsTheUtilizationFunds];
            }
            else{
                obj.layer.borderWidth = 1.0f;
                obj.layer.borderColor = [UIColor colorWithHexString:blueyGrey].CGColor;
                obj.selected = NO;
            }
            
        }];
    }else
    {
        //第一次进来选中第一个
        ((UIButton *)[self.fundBtnArr   firstObject]).selected = YES;
        
    }
    
    
   
}
- (void)setSecurityMoneyArr:(NSMutableArray *)securityMoneyArr
{
    _securityMoneyArr = securityMoneyArr;
    
    _securityMoneyArr = [[NSMutableArray alloc] initWithArray:@[@1250,@1667,@2000]];
    [self.bondBtnArr removeAllObjects];
    for (int i = 0; i < _securityMoneyArr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.bondButtonsView addSubview:button];
        
       
        button.titleLabel.font = [UIFont systemFontOfSize:font12ScreenWRate * LKScreenW];
        button.titleLabel.adjustsFontSizeToFitWidth = YES;

        
        [button setTitle:[NSString stringWithFormat:@"%@", [_securityMoneyArr objectAtIndex:i]] forState:UIControlStateNormal];
        
        //按钮颜色
        [button setTitleColor:[UIColor colorWithHexString:blueyGrey] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        //背景
        [button setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithHexString:fadedOrange]] forState:UIControlStateSelected];
        //边框
        button.layer.cornerRadius = 3.0f;
        button.layer.masksToBounds = YES;
        button.layer.borderWidth = 1.0f;
        button.layer.borderColor = [UIColor colorWithHexString:blueyGrey].CGColor;
        [button addTarget:self action:@selector(bondBtnDidSelected:) forControlEvents:UIControlEventTouchUpInside];
        [self.bondBtnArr addObject:button];
    }
    //水平方向控件间隔固定等间隔
    [self.bondBtnArr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal
                                 withFixedSpacing:rate375(10)
                                      leadSpacing:0
                                      tailSpacing:0];
    
    [self.bondBtnArr mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.bondButtonsView);
        make.height.equalTo(isPhoneX? @(rateX812(24)): @(rate750(24)));
    }];
    
}

- (void)fundBtnDidSelected:(UIButton *)sender
{
    //申请资金为1个时候 无法选择
    if (self.fundBtnArr.count <= 1 ) {
        return;
    }
    [self.fundBtnArr enumerateObjectsUsingBlock:^(UIButton * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.selected = NO;
    }];
    sender.selected  =YES;
    
    if (sender.selected) {
        sender.layer.borderWidth = 1.0f;
        sender.layer.borderColor = [UIColor colorWithHexString:blueyGrey].CGColor;
    }else{
        sender.layer.borderWidth = 1.0f;
        sender.layer.borderColor = [UIColor clearColor].CGColor;
    }
    
    
    if (sender.titleLabel.text.length > 2) {
//        NSString *money = [sender.titleLabel.text substringWithRange:NSMakeRange(0 , sender.titleLabel.text.length -2)];
//        if (self.clickFinishBlock) {
//            self.clickFinishBlock(money);
//        }
    }
    

    YDAccountMonyModel *model = self.fundsArray[sender.tag];
    self.currentMoney = model.wanValue;
}
- (void)bondBtnDidSelected:(UIButton *)sender
{
    [self.bondBtnArr enumerateObjectsUsingBlock:^(UIButton * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.selected = NO;
    }];
    sender.selected  =YES;
}
//购买股票的手数
-(NSInteger)calculationStockHands
{
    NSString *stockPrice = [NSString stringWithFormat:@"%@" , self.stockMarket[@"upLimitPrice"]];
    NSString *currentApplyMoney = [self.currentMoney pz_stringNumberByMultiplyingBy:@"10000"];
    NSString *numberShares = [currentApplyMoney pz_stringNumberByDividingBy:stockPrice];
    DDLog(@"numberShares = %@" , numberShares)
    NSInteger hands = [numberShares integerValue] / 100;
    return hands;
}
//计算资金利用率
-(NSString *)calculationCapitalUtilization
{
    NSString *stockPrice = [NSString stringWithFormat:@"%@" , self.stockMarket[@"upLimitPrice"]];
    NSInteger hands = [self calculationStockHands] * 100;
    NSString *useMoney = [[NSString stringWithFormat:@"%zd",hands] pz_stringNumberByMultiplyingBy:stockPrice];
    NSString *allMoney = [self.currentMoney pz_stringNumberByMultiplyingBy:@"10000"];
    float useRate = (useMoney.floatValue / allMoney.floatValue) * 100;
    NSString *perUseRate = [NSString stringWithFormat:@"%0.2f%%",useRate];
    return perUseRate;
}
-(void)reLoadDetailsTheUtilizationFunds
{
    NSString *stockName = [NSString stringWithFormat:@" %@" , self.stockMarket[@"name"]];
    NSString *handsString = [NSString stringWithFormat:@" %zd " , [self calculationStockHands]];
    NSString *fundRate = [NSString stringWithFormat:@" %@" , [self calculationCapitalUtilization]];
    NSString *string = [NSString stringWithFormat:@"可购买%@%@手，资金利用率%@",stockName , handsString , fundRate];
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange range1 = [string rangeOfString:stockName options:NSCaseInsensitiveSearch];
    NSRange range2 = [string rangeOfString:handsString options:NSCaseInsensitiveSearch];
    NSRange range3 = [string rangeOfString:fundRate options:NSCaseInsensitiveSearch];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:dark] range:range1];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:paleRed] range:range2];
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHexString:paleRed] range:range3];
    self.stockRate.attributedText = str;
}
+ (instancetype)headerViewWithTableView:(UITableView *)tableView
{
    
    static NSString *buyStrategyTableHeaderView = @"YDBuyStrategyTableHeaderView";
    YDBuyStrategyTableHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:buyStrategyTableHeaderView];
    if (headerView == nil) {
        headerView = [[YDBuyStrategyTableHeaderView alloc] initWithReuseIdentifier:buyStrategyTableHeaderView];
    }
    return headerView;
}


-(instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithReuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.contentView.backgroundColor = [UIColor whiteColor];

        [self fundLabel];
        
        [self fundButtonsView];
        
        [self stockRate];
        
        [self lineV1];
        
      //  [self bondLabel];
        
       // [self bondButtonsView];
        
       // [self lineV2];
    }
    return self;
}

-(UILabel *)fundLabel
{
    if (_fundLabel == nil) {
        UILabel *fundLabel = [[UILabel alloc] init];
        [self.contentView addSubview:fundLabel];
        fundLabel.textColor = [UIColor colorWithHexString:blueyGrey];
        fundLabel.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        fundLabel.textAlignment = NSTextAlignmentLeft;
        fundLabel.text = @"申请资金";
        [fundLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(rate375(10));
            if (isPhoneX) {
                make.top.equalTo(self).offset(rateX812(15));
            }else{
                make.top.equalTo(self).offset(rate750(15));
            }
        }];
        _fundLabel = fundLabel;
    }
    return _fundLabel;
}


-(UIView *)fundButtonsView
{
    if (_fundButtonsView == nil) {
        UIView *fundButtonsView = [[UIView alloc] init];
        [self.contentView addSubview:fundButtonsView];
        fundButtonsView.backgroundColor = [UIColor clearColor];
        [fundButtonsView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(rate375(284)));
            make.top.equalTo(self.fundLabel);
            make.left.equalTo(self).offset(rate375(71));
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(62)));
            }else{
                make.height.equalTo(@(rate750(62)));
            }
        }];
        _fundButtonsView = fundButtonsView;
    }
    return _fundButtonsView;
}

-(UILabel *)stockRate
{
    if (_stockRate == nil) {
        UILabel *stockRate = [[UILabel alloc] init];
        [self.contentView addSubview:stockRate];
        stockRate.textColor = [UIColor colorWithHexString:blueyGrey];
        stockRate.font = [UIFont systemFontOfSize:font12ScreenWRate * LKScreenW];
        stockRate.textAlignment = NSTextAlignmentRight;
        stockRate.text = @"申请资金申请资金申请资金申请资金申请资金申请资金";
        
        //NSDictionary *orangeAttribute = @{NSFontAttributeName:[UIFont systemFontOfSize:12],
          //                NSForegroundColorAttributeName:[UIColor colorWithHexString:fadedOrange]};
       
        
        
                                     
        [stockRate mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.right.left.equalTo(self.fundButtonsView);
            if (isPhoneX) {
                make.top.equalTo(self.fundButtonsView.mas_bottom).offset(rateX812(15));
            }else{
                make.top.equalTo(self.fundButtonsView.mas_bottom).offset(rate750(15));
            }
        }];
        stockRate.adjustsFontSizeToFitWidth = YES;
        _stockRate = stockRate;
    }
    return _stockRate;
}

-(UIView *)lineV1
{
    if (_lineV1 == nil) {
        UIView *lineV1 = [[UIView alloc] init];
        [self.contentView addSubview:lineV1];
        lineV1.backgroundColor = NumberColor(247, 247, 247);
        [lineV1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@1);
            make.left.equalTo(self).offset(10);
            make.right.equalTo(self).offset(-10);
            if (isPhoneX) {
                make.top.equalTo(self.stockRate.mas_bottom).offset(rateX812(10));
            }else{
                make.top.equalTo(self.stockRate.mas_bottom).offset(rate750(10));
            }
        }];
        
        
        _lineV1 = lineV1;
    }
    return _lineV1;
}

-(UILabel *)bondLabel
{
    if (_bondLabel == nil) {
        UILabel *bondLabel = [[UILabel alloc] init];
        [self.contentView addSubview:bondLabel];
        bondLabel.textColor = [UIColor colorWithHexString:blueyGrey];
        bondLabel.font = [UIFont systemFontOfSize:font14ScreenWRate * LKScreenW];
        bondLabel.textAlignment = NSTextAlignmentLeft;
        bondLabel.text = @"履约保证金";
        [bondLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(rate375(10));
            if (isPhoneX) {
                make.top.equalTo(self.lineV1.mas_bottom).offset(rateX812(15));
            }else{
                make.top.equalTo(self.lineV1.mas_bottom).offset(rate750(15));
            }
        }];
        _bondLabel = bondLabel;
    }
    return _bondLabel;
}

-(UIView *)bondButtonsView
{
    if (_bondButtonsView == nil) {
        UIView *bondButtonsView = [[UIView alloc] init];
        [self.contentView addSubview:bondButtonsView];
        bondButtonsView.backgroundColor = [UIColor whiteColor];
        [bondButtonsView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(rate375(252)));
            make.left.equalTo(self).offset(rate375(96));
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(24)));
                make.top.equalTo(self.lineV1.mas_bottom).offset(rateX812(10));
            }else{
                make.height.equalTo(@(rate750(24)));
                make.top.equalTo(self.lineV1.mas_bottom).offset(rate750(10));
            }
        }];
        _bondButtonsView = bondButtonsView;
    }
    return _bondButtonsView;
}

-(UIView *)lineV2
{
    if (_lineV2 == nil) {
        UIView *lineV2 = [[UIView alloc] init];
        [self.contentView addSubview:lineV2];
        lineV2.backgroundColor = NumberColor(247, 247, 247);
        [lineV2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@1);
            make.left.equalTo(self).offset(10);
            make.right.equalTo(self).offset(-10);
            make.bottom.equalTo(self);
        }];
    
        _lineV2 = lineV2;
    }
    return _lineV2;
}

- (NSMutableArray *)fundBtnArr
{
    if (!_fundBtnArr) {
        _fundBtnArr = [NSMutableArray new];
    }
    return _fundBtnArr;
}

- (NSMutableArray *)bondBtnArr
{
    if (!_bondBtnArr) {
        _bondBtnArr = [NSMutableArray new];
    }
    return _bondBtnArr;
}


@end
